extends Node

# Autoload to simulate mobile device overlay and touch input when running on desktop.

var enabled: bool = true
var device_width: int = 872
var device_height: int = 1764
var orientation: String = "portrait" # or "landscape"
var frame_texture_path: String = "res://addons/rotto_plugin/frames/frame-horizontal.png"

const EmulatorOverlayScript := preload("res://addons/rotto_plugin/emulator_overlay.gd")

var _overlay_layer: CanvasLayer
var _overlay: Control

func _ready() -> void:
	# Do not run on actual mobile exports.
	var os_name := OS.get_name()
	if os_name == "Android" or os_name == "iOS":
		return

	_enabled_from_settings()
	if not enabled:
		return

	# Compute final size based on orientation.
	var final_size := Vector2i(device_width, device_height)
	if orientation == "landscape":
		final_size = Vector2i(device_height, device_width)
	# Prefer frame texture size if available.
	var used_size := final_size
	if ResourceLoader.exists(frame_texture_path):
		var tex: Texture2D = load(frame_texture_path)
		if tex != null:
			var tex_size := Vector2i(tex.get_size())
			if tex_size.x > 0 and tex_size.y > 0:
				used_size = tex_size

	# Set window size.
	DisplayServer.window_set_size(used_size)

	# Create an overlay layer on top of the game.
	_overlay_layer = CanvasLayer.new()
	_overlay_layer.layer = 100
	add_child(_overlay_layer)

	_overlay = EmulatorOverlayScript.new()
	_overlay.set("device_size", used_size)
	# Try load frame texture if it exists.
	if ResourceLoader.exists(frame_texture_path):
		var tex2: Texture2D = load(frame_texture_path)
		_overlay.set("frame_texture", tex2)
	_overlay_layer.add_child(_overlay)

	# Keep overlay full size when window resizes.
	var window := get_tree().root
	if window.has_signal("size_changed"):
		window.connect("size_changed", Callable(self, "_on_window_size_changed"))

func _enabled_from_settings() -> void:
	# Read project settings if present.
	if ProjectSettings.has_setting("mobile_emulator/enabled"):
		enabled = ProjectSettings.get_setting("mobile_emulator/enabled")
	if ProjectSettings.has_setting("mobile_emulator/width"):
		device_width = int(ProjectSettings.get_setting("mobile_emulator/width"))
	if ProjectSettings.has_setting("mobile_emulator/height"):
		device_height = int(ProjectSettings.get_setting("mobile_emulator/height"))
	if ProjectSettings.has_setting("mobile_emulator/orientation"):
		orientation = String(ProjectSettings.get_setting("mobile_emulator/orientation"))
	if ProjectSettings.has_setting("mobile_emulator/frame_texture_path"):
		frame_texture_path = String(ProjectSettings.get_setting("mobile_emulator/frame_texture_path"))

func _on_window_size_changed() -> void:
	# Ensure overlay keeps full rect.
	if _overlay:
		_overlay.size = get_viewport().size